import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
	{
		path: '/',
		name: 'Home',
		component: () => import('../views/Home.vue'),
		meta: { requiresAuth: false },
	},
	{
		path: '/chat/:roleId?',
		name: 'Chat',
		component: () => import('../views/Chat.vue'),
		meta: { requiresAuth: false },
	},
	{
		path: '/roles',
		name: 'RoleManagement',
		component: () => import('../views/RoleManagement.vue'),
		meta: { requiresAuth: true },
	},
	{
		path: '/roles/create',
		name: 'RoleCreate',
		component: () => import('../views/RoleEditor.vue'),
		meta: { requiresAuth: true },
	},
	{
		path: '/roles/edit/:id',
		name: 'RoleEdit',
		component: () => import('../views/RoleEditor.vue'),
		meta: { requiresAuth: true },
	},
	{
		path: '/profile',
		name: 'Profile',
		component: () => import('../views/Profile.vue'),
		meta: { requiresAuth: true },
	},
	{
		path: '/login',
		name: 'Login',
		component: () => import('../views/Login.vue'),
		meta: { requiresAuth: false },
	},
	{
		path: '/register',
		redirect: '/login'
	},
	{
		path: '/history',
		name: 'History',
		component: () => import('../views/History.vue'),
		meta: { requiresAuth: false },
	},
	{
		path: '/bot',
		name: 'OfficialRobots',
		component: () => import('../views/OfficialRobots.vue'),
		meta: { requiresAuth: false },
	},
]

const router = createRouter({
	history: createWebHistory(),
	routes,
})

// 路由守卫 - 身份验证逻辑
router.beforeEach(async (to, from, next) => {
	const authStore = useAuthStore()

	// 初始化认证状态（从localStorage恢复）
	if (!authStore.token) {
		authStore.initAuth()
	}

	// 检查路由是否需要认证
	if (to.meta.requiresAuth) {
		if (authStore.isAuthenticated) {
			// 已认证，允许访问
			next()
		} else {
			// 未认证，重定向到登录页，并记录原始地址
			next({
				path: '/login',
				query: { redirect: to.fullPath }
			})
		}
	} else {
		// 不需要认证的路由
		if (to.path === '/login' && authStore.isAuthenticated) {
			// 如果已登录用户访问登录页，重定向到首页
			next('/')
		} else {
			next()
		}
	}
})

export default router
